package com.awcall.iot.interceptor;

import com.awcall.iot.common.ResponseResult;
import com.awcall.iot.utils.JwtUtils;
import com.awcall.iot.utils.ResponseUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor extends HandlerInterceptorAdapter {

    private static final Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            return true;
        }

        try {
            Claims claims = JwtUtils.parse(token);
            log.debug("systemUserId: {}", claims.getId());
            request.setAttribute("systemUserId", claims.getId());
        } catch (ExpiredJwtException e) {
            log.error("token过期", e);
            ResponseUtils.writeJson(new ResponseResult(401, "token过期"));
            return false;
        } catch (Exception e) {
            log.error("token非法", e);
            ResponseUtils.writeJson(new ResponseResult(402, "token非法"));
            return false;
        }

        return true;
    }
}
